package com.zhongfu.ai.web;

import com.zhongfu.ai.common.response.Result;
import org.apache.commons.io.FileUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.redisson.api.RList;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.tika.TikaDocumentReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.pgvector.PgVectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.PathResource;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;

@RequestMapping("/api/git")
@RestController
@CrossOrigin("*")
public class GitAnalyzeController {

    private static final Logger log = LoggerFactory.getLogger(GitAnalyzeController.class);
    @Autowired
    private TokenTextSplitter tokenTextSplitter;

    @Autowired
    private PgVectorStore pgVectorStore;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * curl http://localhost:8080/api/git/analyze_git_repository?repoUrl=https://gitee.com/tengyundong_admin/book-clawer.git&userName=tyd0437@163.com&token=password
     * @param repoUrl
     * @param userName
     * @param token
     * @return
     * @throws GitAPIException
     * @throws IOException
     */
    @RequestMapping("/analyze_git_repository")
    public Result analyzeGitRepository(@RequestParam String repoUrl,
                                       @RequestParam String userName,
                                       @RequestParam String token) throws GitAPIException, IOException {

        String localPath = "./git-cloned-repo";
        String repoProjectName = extractProjectName(repoUrl);
        log.info("克隆地址：{}", new File(localPath).getAbsoluteFile());

        FileUtils.deleteDirectory(new File(localPath));

       Git git = Git.cloneRepository().setURI(repoUrl).setDirectory(new File(localPath))
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, token))
                .call();

        Files.walkFileTree(Paths.get(localPath), new SimpleFileVisitor<>(){

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                log.info("遍历路径：{}, 上传知识库：{}", repoProjectName, file.getFileName());

                TikaDocumentReader tikaDocumentReader = new TikaDocumentReader(new PathResource(file));

                List<Document> documentList = tikaDocumentReader.get();

                List<Document> documentSpilterList = tokenTextSplitter.apply(documentList);

                // 添加知识库标签
                documentList.forEach(e->e.getMetadata().put("knowledge", repoProjectName));
                documentSpilterList.forEach(e->e.getMetadata().put("knowledge", repoProjectName));

                pgVectorStore.accept(documentSpilterList);

                return FileVisitResult.CONTINUE;

            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {

                log.info("Failed to access File : {}", file.getFileName());
                return FileVisitResult.CONTINUE;
            }
        });

       // FileUtils.deleteDirectory(new File(localPath));

        // 添加知识库记录
        RList<String> tagList = redissonClient.getList("ragTag");
        if(!tagList.contains(repoProjectName)) {
            tagList.add(repoProjectName);
        }

        git.close();

        log.info("遍历解析路径，上传完成:{}", repoUrl);

        return Result.success(true);

    }

    private String extractProjectName(String repoUrl) {
        String[] parts = repoUrl.split("/");
        String projectNameWithGit = parts[parts.length - 1];
        return projectNameWithGit.replace(".git", "");
    }

}
